package br.edu.utfpr.dao;


import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;

public class Dao<T> {
    protected static EntityManager em  = Persistence.createEntityManagerFactory("UP").createEntityManager();
    private Class clazz;

    public Dao(Class clazz) {
        this.clazz = clazz;
    }
    
    public void inserir(T e) {
        em.getTransaction().begin();
        em.persist(e);
        em.getTransaction().commit();
    }

    public void atualizar(T e) {
        em.getTransaction().begin();
        em.merge(e);
        em.getTransaction().commit();
    }

    public void remover(Integer id) {
        T e = obter(id);
        if (e != null) {
            em.getTransaction().begin();
            em.remove(e);
            em.getTransaction().commit();
        }
    }

    public T obter(Integer id) {
        return (T) em.find(clazz, id);
    }

    public List<T> listar() {
        return em.createQuery("select e from "+clazz.getSimpleName() + " e").getResultList();
    }
}
